<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElTable, ElTableColumn } from "element-plus";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/store/token.js";
import router from "@/router";
import {
  courseList,
  courseNameList,
  // courseIdList,
  directionList,
  courseUserIdList,
  aaaaa,
  saveCourse,
  professional,
  direction,
} from '@/api/common/work/courseManager.js';

const ret01 = useTokenStore();

const coursesMoudle = ref({
  directionId: "",
  courseName: "",
  directionName: [],
  createUser: "",
  updateTime: "",
});
const userInfo = ref({});
const getUserInfos = async () => {
  let reult = await aaaaa();
  // console.log(reult)
  userInfo.value = reult.data;
  console.log(userInfo.value.userId);
  getAllCourse(userInfo.value.userId)
};
getUserInfos();

const directions = ref([]);
const getAlldirections = async () => {
  let result = await directionList();
  directions.value = result.data;
};
getAlldirections();
const courses = ref([]);
const getAllCourse = async (e) => {
  console.log(e);
   let result = await courseList(e);
   courses.value = result.data; 
  courses.value.forEach((res) => {
    let userId = userInfo.value.userId;
    if (userId === res.createUser) {
      res.isEdit = true;
    } else {
      res.isEdit = false;
    }
  });

  console.log(courses.value);
};

const courseName = ref("");
const getNameCourseList = async () => {
  if (courseName.value == "") {
    await getAllCourse();
  } else {
    let result = await courseNameList(courseName.value);
    courses.value = result.data;
  }
};

const push = () => {
  router.push("/course/Course");
};

const push1 = (id) => {
  router.push({
    path: "/course/Course",
    query: { courseId: id }, // 序列化对象，如果需要的话
  });
};

const push2 = (row) => {
  router
    .push({
      path: "/authorization/ClassAuthorization",
      query: { courseData: JSON.stringify(row) }, // 序列化对象，如果需要的话
    })
    .catch((err) => {
      // 处理导航错误
      console.error("Navigation failed:", err);
    });
};

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);

const textarea = ref("");

const form = reactive({
  courseName: "",
  directionId: "",
  professionalId: "",
});

//查询专业课程
const professionals = async () => {
  let res = await professional();

  for (let i = 0; i < res.data.length; i++) {
    options.push({
      value: res.data[i].professionalId,
      label: res.data[i].professionalName,
    });
  }
};

professionals();

const initials = [];
// 查询专业方向
const directionss = async () => {
  let res = await direction();

  for (let i = 0; i < res.data.length; i++) {
    initials.push({
      value: res.data[i].directionId,
      label: res.data[i].directionName,
    });
  }
};
directionss();

const options = [];

const directionData = ref([]);

const form2 = ref({
  courseName: "",
  directionId: "",
  professionalId: "",
  courseInfo: "",
  lessonHours: "",
});

//清空数据
const form1 = () => {
  (form2.value.courseName = ""),
    (form2.value.directionId = ""),
    (form2.value.professionalId = ""),
    (form2.value.courseInfo = ""),
    (form2.value.lessonHours = "");
};

//多选校验规则
// extend('requiredArray', {  


//   params: ['target'],  
//   validate(directionData, { target }) {  
//     if (Array.isArray(directionData) && directionData.length > 0) {  
//       return true;  
//     }  
//     return `${target || '字段'}至少需要选择一个选项。`;  
//   },  
//   message: '字段 {_field_} 是必填的'  
// });  


//新增课程的数据校验
const rules = {
  courseName: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
  professionalId: [
    { required: true, message: "请选择专业课程", trigger: "blur" },
  ],
  directionId: [{ required: true, message: "请选择专业方向", trigger: "blur" }],
  courseInfo: [{ required: true, message: "课程简介", trigger: "blur" }],
  lessonHours: [
    { required: true, message: "课时", trigger: "blur" },
    {
      type: "number",
      message: "课时数必须是数字",
      trigger: ["blur", "change"],
    },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("课时数不能为负数或0"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"]
    }
  ],
};


//课程校验
const fromRef = ref(null)


//校验课程是否通过
const courseInfos = () => {
  fromRef.value.validate((valid) => {
    if (valid) {
      if (form2.value.professionalId == '' || form2.value.professionalId == undefined) {
        ElMessage.error("请选择专业课程");
      } else {
        save()
        setTimeout(() => {
          location.reload()
        }, 800)
      }

    } else {
      return false;
    }
  });

}


//新增课程
const save = async () => {
  if (directionData.value == null || directionData.value == undefined || directionData.value.length == 0) {
    ElMessage.error("请选泽专业方向");
  } else {
    for (let i = 0; i < directionData.value.length; i++) {
      form2.value.directionId += directionData.value[i] + ",";
    }
    if (form2.value != null) {
      let result = await saveCourse(form2.value);
      console.log(form2.value);
      console.log(directionData.value);
      //隐藏弹框
      dialogFormVisible.value = false;
      //清空数据
      form1();

      ElMessage.success("新增课程成功");
    }
  }

};
//点击取消清除数据
const quxiao = () => {
  dialogFormVisible.value = false;
  form1();
};

const handleBlur = async () => {
  // 检查课程名是否重复的逻辑

  const isDuplicate = await form2.value.courseName;
  for (let i = 0; i < courses.value.length; i++)
    //判断课程名是否重复
    if (isDuplicate == courses.value[i].courseName) {
      // 如果课程名重复，则显示错误消息
      ElMessage.error("课程名已存在！");
    }
};

</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="
          border-bottom: 1px solid #ccc;
          background-color: #fff;
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
        <div class="common-layout-header-title" style="flex-shrink: 0; padding-left: 10px">
          课程管理
        </div>
        <div style="display: flex; align-items: center">
          <el-button plain type="primary" size="small" @click="dialogFormVisible = true"
            style="margin-right: 10px; height: 30px; line-height: 32px">
            新建课程
          </el-button>
          <!-- <el-select  
      placeholder="请选择"  
      v-model="directionId"  
      style="margin-right: 10px; width: 150px;height:30px"  
      @change="courseIdByList()"
    >  
      <el-option  
        v-for="c in directions"  
        :key="c.directionId"  
        :label="c.directionName"  
        :value="c.directionId"  
      ></el-option>  
    </el-select>   -->
          <el-input placeholder="请输入内容" size="small" v-model="courseName"
            style="margin-right: 10px; width: 150px; height: 30px" />
          <el-button type="primary" @click="getNameCourseList" style="margin-left: 0; height: 30px">
            搜索
          </el-button>
        </div>
      </el-header>
      <el-main class="common-layout-main">
        <el-table  :data="courses" >
          <el-table-column prop="courseName" label="课程名称" ></el-table-column>
          <el-table-column prop="nickName" label="创建者"></el-table-column>
          <el-table-column prop="createTime" label="创建日期"></el-table-column>
          <el-table-column prop="directionName" label="方向"></el-table-column>
          <el-table-column prop="permission" label="授权管理"><template #default="{ row }">
              <span @click="push2(row)" style="cursor:pointer">班级授权</span>
            </template>
          </el-table-column>
          <el-table-column prop="manage" label="管理">
            <template #default="{ row }">
              <span  @click="row.isEdit ? push1(row.courseId) : null">
                <strong>编辑</strong>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>

  <el-form>
    <el-drawer v-model="dialogFormVisible" :with-header="false">
      <div class="dialog-title">创建课程</div>
      <el-form :model="form2" :rules="rules" ref="fromRef">
        <el-form-item label="课程名称：" prop="courseName">
          <el-input v-model="form2.courseName" type="courseName" />
        </el-form-item>
        <el-form-item label="课程时长：" prop="lessonHours">
          <el-input-number v-model="form2.lessonHours" type="lessonHours" />
        </el-form-item>
        <el-form-item label="专业课程：" style="width: 450px; margin-left: 10px">
          <el-select v-model="form2.professionalId" clearable prop="professionalId" placeholder="--请选择--"
            style="width: 365px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="专业方向：" style="width: 450px; margin-left: 10px">
          <el-select-v2 v-model="directionData" :options="initials" placeholder="--请选择--" style="width: 365px"
            multiple />
        </el-form-item>
        <el-form-item label="课程介绍：" prop="courseInfo">
          <el-input v-model="form2.courseInfo" :rows="8" type="textarea" class="no-resize" />
        </el-form-item>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="quxiao">取消</el-button>
        <el-button type="primary" @click="courseInfos" style="background-color: #ee3b3b; border: 0">
          提交
        </el-button>
      </div>
    </el-drawer>
  </el-form>
</template>

<style>
.cming {
  color: rgba(4, 4, 156, 0.479);
  cursor: pointer;
}

.sming {
  display: none;
}

.no-resize {
  resize: none;
}

.bianji {
  cursor: pointer;
}

.common-layout-header-title {
  margin-top: 20px;
}

.common-layout-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
}

.common-layout-header-button {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.dialog-footer {
  margin-top: 50px;
  margin-left: 220px;
}

.dialog-title {
  /* border: 1px solid red; */
  width: 200px;
  height: 50px;
  font-size: 24px;
  margin-left: 5px;
}

.el-form-item__label {
  height: 32px;
  line-height: 32px;
  margin-top: 20px;
}
</style>
